package cn.hjc.dao;

import cn.hjc.entity.Dept;
import cn.hjc.entity.Emp;
import cn.hjc.entity.EmpCondition;
import org.hibernate.Query;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

public class EmpDao extends BaseDao {
    public List<Emp> findAll(){
        return   this.currentSession().createQuery("from Emp").list();//构建Query

    }

    public List<Emp> findByConditions(Object[] conditions){
        //查询依赖多个条件，且类型各异
        String hql = "from Emp where job = ? and sal >?";
        Query query = currentSession().createQuery(hql);
        if(conditions !=null && conditions.length>0){
            for ( int i =0;i<conditions.length;++i){
                query.setParameter(i,conditions[i]);//为占位符赋值
            }
        }
        return  query.list();
    }

    public List<Emp> findByConditions(String hql, EmpCondition conditions){
        return currentSession().createQuery(hql) // 创建Query对象
                .setProperties(conditions) // 为参数赋值
                .list(); // 执行查询，获取查询结果
    }
    public Long obtainTheRowCount(Double sal){
        String hql = "select count(id) from Emp where sal >= :sal";
        return (Long) currentSession().createQuery(hql)
                .setDouble("sal",sal)
                .uniqueResult();//执行返回唯一结果，以Object类型封装
    }

    public List<Emp> findByPage(int pageNo,int pageSize){
        return  currentSession().createQuery("from Emp  order by id")
                .setFirstResult((pageNo-1) * pageSize)  //设置获取结果的起始下标
                .setMaxResults(pageSize)//设置最大返回结果数
                .list();
    }

    public void save(Emp emp){
        this.currentSession().save(emp);
    }

    public List<Emp> findByDept(Dept dept){
        String hql = "from Emp where dept = ?";
        return this.currentSession().createQuery(hql).setParameter(0,dept).list();

    }
    public Emp load(Serializable empNo){
        return (Emp)this.currentSession().load(Emp.class,empNo);
    }

}
